package net.lab1024.sa.admin.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import javax.print.PrintService;
import java.awt.print.*;
import java.io.File;
import java.io.IOException;

public class PrintUtil {

    public static void print(String path,String macName,int printNum) throws IOException, PrinterException, InterruptedException {

        File file = new File(path);
        int pageCount = 0;
        PrinterJob job = PrinterJob.getPrinterJob();
        // 遍历所有打印机的名称
        for (PrintService ps : PrinterJob.lookupPrintServices()) {
            // 选用指定打印机
            if (ps.getName().equals(macName)) {
                job.setPrintService(ps);
                break;
            }
        }
        // 读取pdf文件
        PDDocument document = null;
        document = PDDocument.load(file);
        pageCount = document.getNumberOfPages();
        job.setPageable(new PDFPageable(document));
        Paper paper = new Paper();
        // 设置打印纸张大小
        paper.setSize(598, 842); // 1/72 inch
        // 设置打印位置 坐标
        paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margins
        // custom page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        // override the page format
        Book book = new Book();
        // append all pages 设置一些属性 是否缩放 打印张数等
        book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, pageCount);
        job.setPageable(book);
        // 开始打印
        for (int i = 0; i < printNum; i++) {
            job.print();
        }
        //创建打印任务
        document.close();
    }
}
